package cn.jasonone.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.jasonone.bean.UserInfo;
import cn.jasonone.util.DBUtil;

public class UserInfoDao {

	private UserInfo parseBean(ResultSet rs) throws SQLException {
		UserInfo user = new UserInfo();
		user.setId(rs.getInt("id"));
		user.setUsername(rs.getString("username"));
		user.setPassword(rs.getString("password"));
		user.setCreateTime(rs.getDate("create_time"));
		user.setUpdateTime(rs.getDate("update_time"));
		user.setStatus(rs.getInt("status"));
		return user;
	}

	public UserInfo login(UserInfo user) {
		String sql = "select * from  user_info where username=? and password=md5(?)";
		try (Connection conn = DBUtil.getConnection()) {
			try (PreparedStatement ps = conn.prepareStatement(sql)) {
				ps.setString(1, user.getUsername());
				ps.setString(2, user.getPassword());
				try (ResultSet rs = ps.executeQuery()) {
					if (rs.next()) {
						return this.parseBean(rs);
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public boolean register(UserInfo user) {
		String sql = "insert into user_info(username,password,create_time,status) values(?,md5(?),now(),?)";
		try (Connection conn = DBUtil.getConnection()) {
			try (PreparedStatement ps = conn.prepareStatement(sql)) {
				ps.setString(1, user.getUsername());
				ps.setString(2, user.getPassword());
				ps.setInt(3, user.getStatus());
				return ps.executeUpdate() > 0;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}
}
